<template>
	<view class="coupon-container">
		<view class="coupon-list">
			<!-- 优惠券列表项 -->
			<view v-for="coupon in couponList" :key="coupon.id"
				:class="['coupon-item', { 'disabled-coupon': coupon.is_use !== 0 || coupon.is_expired }]">
				<view class="coupon-left">
					<view class="coupon-price">
						<text class="price-symbol">¥</text>
						<text class="price-num">{{coupon.money}}</text>
					</view>
					<view class="coupon-type">{{coupon.coupon_type}}</view>
					<view class="coupon-name">{{coupon.coupon_name}}</view>
				</view>
				<view class="coupon-right">
					<view class="coupon-time">
						{{formatDate(coupon.use_start_time)}}-
						{{formatDate(coupon.use_end_time)}}
					</view>
					<view class="coupon-status" v-if="coupon.is_use === 1">
						已使用
					</view>
					<view class="coupon-status" v-else-if="coupon.is_expired">
						已过期
					</view>
					<view v-else>
						<button class="use-btn" @click="useCoupon(coupon)"
							:disabled="coupon.is_use === null || coupon.is_expired">立即使用</button>
					</view>
				</view>
			</view>
			<!-- 无数据提示 -->
			<view class="no-data" v-if="couponList.length === 0 && !loading">
				暂无优惠券
			</view>
			<!-- 加载中提示 -->
			<view class="loading" v-if="loading">
				加载中...
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getUserCoupon,
		getCoupon
	} from '../../api/request';

	export default {
		data() {
			return {
				couponList: [],
				page: 1,
				total: 0,
				loading: false,
				hasMore: true,
				pg: '',
				goodsData: null
			};
		},
		// 加载更多
		onReachBottom() {
			this.page++;
			if (that.pg == '') {
				that.loadCouponList();
			} else {
				that.loadCouponData(that.goodsData)
			}
		},

		onLoad(options) {
			console.log(options)
			// 监听滚动到底部加载更多
			this.bindScrollToLower();
			if (options.page) {
				this.pg = options.page;
				this.goodsData = options.goodsData;
				this.loadCouponData(this.goodsData)
			} else {
				this.loadCouponList();
			}
		},
		methods: {
			// 加载优惠券数据
			loadCouponData(goodsData) {
				try {
					// 尝试解析传递过来的JSON字符串
					let parsedData = goodsData;
					if (typeof goodsData === 'string') {
						try {
							parsedData = JSON.parse(decodeURIComponent(goodsData));
						} catch (e) {
							console.warn('解析goodsData失败，使用原始数据:', e);
						}
					}
					const jsonData = JSON.stringify(parsedData);

					getCoupon({
						page: 1,
						data: jsonData
					}).then(res => {
						console.error('getCoupon', res);
						if (res.code === 1 && res.data && res.data.rows) {
							console.error('获取优惠券失败', res);
							const newCoupons = res.data.rows || [];
							// 处理goods_ids字段，将字符串转为数组
							newCoupons.forEach(coupon => {
								try {
									coupon.goods_ids = JSON.parse(coupon.goods_ids);
								} catch (e) {
									coupon.goods_ids = [];
								}
							});

							if (this.page === 1) {
								this.couponList = newCoupons;
							} else {
								this.couponList = [...this.couponList, ...newCoupons];
							}

							this.total = res.data.total;
							this.hasMore = this.couponList.length < this.total;
							this.page++;
						} else {
							uni.showToast({
								title: res.msg || '获取优惠券失败',
								icon: 'none'
							});
						}
					}).catch(err => {
						console.error('获取优惠券失败', err.data);
					});
				} catch (error) {
					console.error('loadCouponData方法出错:', error);
					console.error('错误堆栈:', error.stack);
				}
			},
			// 加载优惠券列表
			loadCouponList() {
				if (this.loading || !this.hasMore) return;

				this.loading = true;
				getUserCoupon({
						page: this.page
					})
					.then(res => {
						if (res.code === 1 && res.data) {
							console.error('获取优惠券失败', res);
							const newCoupons = res.data.rows || [];
							// 处理goods_ids字段，将字符串转为数组
							newCoupons.forEach(coupon => {
								try {
									coupon.goods_ids = JSON.parse(coupon.goods_ids);
								} catch (e) {
									coupon.goods_ids = [];
								}
							});

							if (this.page === 1) {
								this.couponList = newCoupons;
							} else {
								this.couponList = [...this.couponList, ...newCoupons];
							}

							this.total = res.data.total;
							this.hasMore = this.couponList.length < this.total;
							this.page++;
						} else {
							uni.showToast({
								title: res.msg || '获取优惠券失败',
								icon: 'none'
							});
						}
					})
					.catch(err => {
						console.error('获取优惠券失败', err);
						uni.showToast({
							title: '获取优惠券失败',
							icon: 'none'
						});
					})
					.finally(() => {
						this.loading = false;
					});
			},

			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return '';
				const date = new Date(dateString);
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
			},

			// 使用优惠券
			useCoupon(coupon) {
				// 判断是否从订单确认页面进来
				if (this.pg === 'sureOrder') {
					// 存储优惠券信息到全局事件总线
					uni.$emit('selectCoupon', {
						coupon_id: coupon.id,
						coupon_name: coupon.coupon_name,
						money: coupon.money
					});
					// 返回上一页
					uni.navigateBack();
				} else {
					// 原有跳转逻辑
					if (!coupon.goods_ids || coupon.goods_ids.length === 0 || coupon.goods_ids.length > 1) {
						// 跳转到首页
						uni.switchTab({
							url: '/pages/index/index'
						});
					} else {
						// 跳转到商品详情
						uni.navigateTo({
							url: `/pages/goods/detail?goods_id=${coupon.goods_ids[0]}`
						});
					}
				}
			},

			// 绑定滚动到底部事件
			// bindScrollToLower() {
			// 	var that = this;
			// 	uni.createIntersectionObserver()
			// 		.relativeToViewport({
			// 			bottom: 100
			// 		})
			// 		.observe('.coupon-list', res => {
			// 			if (res.intersectionRatio > 0) {
			// 				if (that.pg=='') {
			// 					that.loadCouponList();
			// 				}else{
			// 					that.loadCouponData(that.goodsData)
			// 				}
			// 			}

			// 		});
			// }
		}
	};
</script>

<style scoped lang="scss">
	.coupon-container {
		padding: 20rpx;
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.coupon-list {
		width: 100%;
	}

	.coupon-item {
		display: flex;
		background: linear-gradient(135deg, #ff6b6b 0%, #ff4b4b 100%);
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		color: #fff;
		position: relative;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(255, 75, 75, 0.2);
	}

	.coupon-item.disabled-coupon {
		background: linear-gradient(135deg, #cccccc 0%, #999999 100%);
		box-shadow: 0 4rpx 12rpx rgba(153, 153, 153, 0.2);
		color: #666;
	}

	.coupon-item::before {
		content: '';
		position: absolute;
		top: 0;
		right: 0;
		width: 160rpx;
		height: 160rpx;
		background: rgba(255, 255, 255, 0.1);
		border-radius: 50%;
		transform: translate(60rpx, -60rpx);
	}

	.coupon-left {
		flex: 1;
		z-index: 1;
	}

	.coupon-price {
		display: flex;
		align-items: flex-end;
		margin-bottom: 10rpx;
	}

	.price-symbol {
		font-size: 32rpx;
		margin-right: 5rpx;
	}

	.price-num {
		font-size: 64rpx;
		font-weight: bold;
		line-height: 1;
	}

	.coupon-type {
		font-size: 24rpx;
		background-color: rgba(255, 255, 255, 0.2);
		padding: 5rpx 10rpx;
		border-radius: 15rpx;
		display: inline-block;
		margin-bottom: 10rpx;
	}

	.coupon-name {
		font-size: 28rpx;
		font-weight: 500;
	}

	.coupon-right {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: space-between;
		z-index: 1;
		padding-left: 20rpx;
	}

	.coupon-time {
		font-size: 24rpx;
		margin-bottom: 20rpx;
		text-align: right;
	}

	.coupon-status {
		font-size: 28rpx;
		color: #ff9900;
		font-weight: bold;
		padding: 10rpx 20rpx;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 8rpx;
	}

	.use-btn:disabled {
		background-color: #ccc;
		color: #666;
		pointer-events: none;
	}

	.use-btn {
		background-color: #fff;
		color: #ff4b4b;
		font-size: 28rpx;
		padding: 8rpx 24rpx;
		border-radius: 30rpx;
		margin-top: 15rpx;
		font-weight: 500;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.use-btn:active {
		transform: scale(0.98);
	}

	.no-data {
		text-align: center;
		padding: 60rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.loading {
		text-align: center;
		padding: 30rpx 0;
		color: #999;
		font-size: 28rpx;
	}
</style>